<?php

namespace App\Services\Admin\Sponsor;

use App\Exceptions\SponsorException;
use App\Exceptions\UserException;
use App\Models\Applet\Order\SponsorOrderModel;
use App\Models\Applet\User\UserIntegralRecordsModel;
use Exception;
use Illuminate\Support\Facades\DB;

class SponsorService extends BaseSponsorService
{

    /**
     * 认养列表
     * @param array $params
     * @return array[]
     * @throws Exception
     */
    public function list(array $params): array
    {
        $total = $this->getUserSponsorModel()->total($params);

        // 查询认养列表
        $sponsorList = $this->getUserSponsorModel()->list($params, [
            'user_sponsor.id', 'user_id', 'order_id', 'ranch_id', 'user_sponsor.name',
            'user_sponsor.cover_img', 'user_sponsor.quantity', 'user_sponsor.start_time',
            'user_sponsor.cycle', 'user_sponsor.status'
        ]);

        $ranchIds = array_column($sponsorList, 'ranch_id');
        $ranchList = $this->getStoreRanchModel()->getItemsByIds($ranchIds, [
            'id', 'name'
        ]);

        $ranchListMap = array_column($ranchList, null, 'id');

        // 查询用户信息
        $userIds = array_column($sponsorList, 'user_id');
        $userList = $this->getUserModel()->getItemsByIds($userIds, ['id', 'nickname', 'avatar', 'phone']);
        $userListMap = array_column($userList, null, 'id');

        $userSlaughterRecordsIds = array_column($sponsorList, 'id');
        // 查询认养已发总积分
        $slaughterIntegralTotalList = $this->getUserIntegralRecordsModel()->getTotalBySourceId($userSlaughterRecordsIds, UserIntegralRecordsModel::SOURCE_TYPE_USER_SPONSOR);

        $slaughterIntegralTotalListMap = array_column($slaughterIntegralTotalList, 'count', 'source_id');

        $list = [];
        foreach ($sponsorList as $item) {

            $integralTotal = $slaughterIntegralTotalListMap[$item['id']] ?? 0;

            $list[] = [
                'id' => $item['id'],
                'orderId' => $item['order_id'],
                'nickname' => $userListMap[$item['user_id']]['nickname'] ?? '用户不存在或已注销',
                'avatar' => $userListMap[$item['user_id']]['avatar'] ?? '',
                'phone' => $userListMap[$item['user_id']]['phone'] ?? '',
                'startTime' => $item['start_time'],
                'cycle' => $item['cycle'],
                'goodsName' => $item['name'],
                'quantity' => $item['quantity'],
                'ranchInfo' => $ranchListMap[$item['ranch_id']] ?? null,
                'status' => $item['status'],
                'integralTotal' => intval($integralTotal),
            ];
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 发放积分
     * @param array $params
     * @return void
     * @throws SponsorException
     * @throws UserException
     * @throws Exception
     */
    public function grantIntegral(array $params)
    {
        // 查询用户认养记录
        $userSponsor = $this->getUserSponsorModel()->getItemById($params['id'], [
            'id', 'user_id'
        ]);
        if (empty($userSponsor)) {
            throw new SponsorException('用户认养记录不存在', SponsorException::CODE_4001);
        }

        // 查询用户
        $userInfo = $this->getUserModel()->getItemById($userSponsor['user_id'], [
            'id', 'integral'
        ]);
        if (empty($userInfo)) {
            throw new UserException('用户不存在', UserException::CODE_1003);
        }

        // 发放积分
        $createUserIntegralData = [
            'user_id' => $userInfo['id'],
            'type' => UserIntegralRecordsModel::TYPE_INCREMENT,
            'source_type' => UserIntegralRecordsModel::SOURCE_TYPE_USER_SPONSOR,
            'source_id' => $params['id'],
            'quantity' => $params['quantity'],
            'remark' => $params['remark'] ?? '',
        ];

        $createSponsorUserIntegralData = [
            'sponsor_id' => $params['id'],
        ];

        DB::transaction(function () use ($createUserIntegralData, $createSponsorUserIntegralData, $userInfo, $params) {
            // 添加用户积分记录
            $userIntegralId = $this->getUserIntegralRecordsModel()->addItemGetId($createUserIntegralData);
            // 添加认养用户积分记录
            $createSponsorUserIntegralData['user_integral_id'] = $userIntegralId;
            $this->getSponsorIntegralRecordsModel()->addItem($createSponsorUserIntegralData);
            // 更新用户积分
            $this->getUserModel()->updateItemById($userInfo['id'], [
                'integral' => $userInfo['integral'] + $params['quantity']
            ]);
        });
    }

    /**
     * 绑定牧场
     * @return void
     * @throws SponsorException
     * @throws Exception
     */
    public function bindRanch(array $params)
    {
        // 查询用户认养记录
        $userSponsor = $this->getUserSponsorModel()->getItemById($params['id'], [
            'id', 'user_id', 'order_id'
        ]);
        if (empty($userSponsor)) {
            throw new SponsorException('用户认养记录不存在', SponsorException::CODE_4001);
        }

        // 查询牧场
        $ranchInfo = $this->getStoreRanchModel()->getItemById($params['ranchId']);
        if (empty($ranchInfo)) {
            throw new SponsorException('牧场不存在', SponsorException::CODE_4001);
        }

        DB::transaction(function () use ($userSponsor, $ranchInfo, $params) {
            // 绑定关系
            $this->getUserSponsorModel()->updateItemById($userSponsor['id'], [
                'ranch_id' => $ranchInfo['id']
            ]);
            // 将订单置为已完成状态
            $this->getSponsorOrderModel()->updateItemById($userSponsor['order_id'], [
                'order_status' => SponsorOrderModel::ORDER_STATUS_COMPLETED,
            ]);
        });
    }
}
